﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Security.Principal;
using Dapper.Core;

namespace Dapper.Web
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            string Dapper_AuthCode = Cookies.Get(FormsAuthentication.FormsCookieName);

            if (string.IsNullOrEmpty(Dapper_AuthCode))
            {
                return;
            }
            FormsAuthenticationTicket authTicket = null;

            //获取验证票据。
            authTicket = FormsAuthentication.Decrypt(Dapper_AuthCode);

            if (null == authTicket)
            {
                return;
            }

            //验证票据的UserData中存放的是用户角色信息。
            //UserData本来存放用户自定义信息。此处用来存放用户角色。
            string[] roles = authTicket.UserData.Split(',');

            FormsIdentity id = new FormsIdentity(authTicket);

            GenericPrincipal principal = new GenericPrincipal(id, roles);

            //把生成的验证票信息和角色信息赋给当前用户．
            Context.User = principal;
        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}